import React, { useEffect, useState } from 'react'
import ProForm, { ProFormDigit, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';
import { Modal, Skeleton, Cascader, Button, Image } from 'antd';
import { addUser, showUsers, updateUser } from '@/services/userList'
import { message } from 'antd';
import Form from 'antd/lib/form/Form';
import { getCategory } from '@/services/category';
import AliyunOSSUpload from '@/components/AliyunOSSUpload'
import { UploadOutlined } from '@ant-design/icons';
import Editor from '@/components/Editor'
import { addGoods, showGoods, updateGoods } from '@/services/goods';

export default function CreateOrEdit(props) {
  //表单数据
  const [initialValues, setInitialValues] = useState(undefined)
  const [options, setOptions] = useState([])
  //定义form实例，用来操作表单
  const [formObj] = ProForm.useForm()

  //模态框是否显示
  //操作模态框显示隐藏的方法
  //父组件的传递过来的表格的引用，可以用来操作表格，比如刷新表格
  //要编辑的ID，添加的时候用undefined，只有编辑才有值
  const { isModalVisible, isShowModal, actionRef, editId } = props
  //添加或编辑的文字类型
  const type = editId === undefined ? '添加' : '编辑';
  //文件上传之后设置cover的value
  const setCoverKey = fileKey => {
    //设置表单的值
    formObj.setFieldsValue({ 'cover': fileKey })
  }
  //编辑输入内容，设置details字段的value
  const setDetails = content => {
    //设置表单的值
    formObj.setFieldsValue({ 'details': content })
  }
  //提交表单，执行编辑或添加
  const handleSubmit = async values => {
    console.log(values);
    let res = {}
    if (editId === undefined) {
      //发送请求，添加用户
      console.log(1);
      res = await addGoods({ ...values, category_id: values.category_id[1] })
      console.log(3);
    } else {
      //发送请求，更新用户
      console.log(2);
      res = await updateGoods(editId, { ...values, category_id: values.category_id[1] })
    }
    if (res.status === undefined) {
      message.success(`${type}成功`)
      //刷新表格数据
      actionRef.current.reload()
      //关闭模态框
      isShowModal(false)
    }
  }

  useEffect(() => {
    const getCategoryList = async () => {
      const res = await getCategory()
      if (res.status === undefined) {
        setOptions(res)
      }
    }
    const getOneGood = async () => {
      if (editId !== undefined) {
        const res = await showGoods(editId)
        console.log(res);
        //获取数据之后，修改状态，状态改变，组件重新渲染，骨架屏消失，表单出现
        const { pid, id } = res.category
        const defaultCategory = pid === 0 ? [id] : [pid, id]
        setInitialValues({ ...res, category_id: defaultCategory })
      }
    }
    getCategoryList()
    getOneGood()
  }, [])
  return (
    <Modal title={`${type}商品`} visible={isModalVisible}
      onCancel={() => isShowModal(false)} footer={null} destroyOnClose={true}>
      {
        //只有在编辑的情况下，并且要显示的数据还没有返回，才显示骨架屏
        initialValues === undefined && editId !== undefined ? <Skeleton active={true} paragraph={{ rows: 2 }} /> :
          <ProForm
            form={formObj}
            initialValues={initialValues}
            onFinish={values => handleSubmit(values)}
          >
            <ProForm.Item label="分类" name="category_id" rules={[{ required: true, message: '请选择分类' }]}>
              <Cascader options={options} placeholder="请选择分类" fieldNames={{ label: 'name', value: 'id' }} />
            </ProForm.Item>
            <ProFormText
              name="title"
              label="名称"
              placeholder="请输入名称"
              rules={[{ required: true, message: '请输入名称' }]}
            />
            <ProFormTextArea
              name="description"
              label="描述"
              placeholder="请输入描述"
              rules={[{ required: true, message: '请输入描述' }]}
            />
            <ProFormDigit
              name="price"
              label="价格"
              placeholder="请输入价格"
              min={0}
              max={999999999}
              rules={[{ required: true, message: '请输入库存' }]}
            />
            <ProFormDigit
              name="stock"
              label="库存"
              placeholder="请输入库存"
              min={0}
              max={999999999}
              rules={[{ required: true, message: '请输入价格' }]}
            />

            <ProForm.Item name="cover" label="商品主图" rules={[{ required: true, message: '请上传商品主图' }]}>
              <div>
                <AliyunOSSUpload accept="image/*" setCoverKey={setCoverKey} showUploadList={true}>
                  <Button icon={<UploadOutlined />}>点击上传商品主图</Button>
                </AliyunOSSUpload>
                {
                  initialValues === undefined || !initialValues.cover_url ? '' :
                    <Image width={100} src={initialValues.cover_url} />
                }
              </div>
            </ProForm.Item>
            <ProForm.Item name="details" label="商品详情" rules={[{ required: true, message: '请输入商品详情' }]}>
              <Editor setDetails={setDetails} content={initialValues === undefined ? '' : initialValues.details} />
            </ProForm.Item>

          </ProForm>
      }

    </Modal>
  )
}
